﻿using Newtonsoft.Json;

namespace EasyXaf.LowCode.RulesEngineEditors.Models;

public class ExpressionTypeConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(ExpressionType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return FromString(reader.Value as string);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteValue(ToString((ExpressionType)value));
    }

    public static ExpressionType FromString(string value)
    {
        return value switch
        {
            "criteria" => ExpressionType.Criteria,
            _ => ExpressionType.Lambda
        };
    }

    public static string ToString(ExpressionType value)
    {
        return value switch
        {
            ExpressionType.Criteria => "criteria",
            _ => "lambda"
        };
    }
}
